// Dossier

var XML_DSS={
  DOSCACHE:0,
  CACHEROOT:0,
  CACHEFILE:"data/dcache.xml",
  CACHEDIR:"",
  CACHEARRAY:[],
  _setdossiersort:antidossiersortnum
};


//------------------------------------------------------------------------------------------


function SaveDossier(name) {
  XMLDOMDOS.save(GetDossiersDir()+name+".xml");
  updatedossiercache();
  start_autosave();
}

function BackUpDossier(name) {
  XMLDOMDOS.save(GetDossiersDir()+name+".bak");
}

function RestoreDossier(name) {
  if(dos_isfile(GetDossiersDir()+name+".bak")) {
    LoadDossier(name,"",".bak");
  } else {
    alert("No backup available for dossier "+name);
  }
}

// back end function for loading
XML_DSS._LoadDossier=function(name,opt,ext) {
  var fname=GetDossiersDir()+name+(ext || ".xml");
  // check file exists
  if(!dos_isfile(fname)) {
    if(!opt) alert(name +" dossier not found !");
    return 0;
  }
  // load file
  XMLDOMDOS.load(fname);
  // Errors while parsing xml ?
  if(XMLDOMDOS.parseError.errorCode != 0) {
    if(!opt) alert(name+" corrupted ! Check for non ASCII symbols in file "+fname);
    return 0;
  }
  SetDossier(XMLDOMDOS.selectSingleNode('dossier'));
  return 1;
}

function LoadDossier(name,opt,ext) {
  if(XML_DSS._LoadDossier(name,opt,ext)) {
    CLAIMSET=null;
    DOCS=DOSSIER.selectSingleNode('documents').childNodes;
    GetClaimSets();
    // refresh used docs from global library
    UpdateDocsFromDB();

    // import caesar citations
    CaesarImportCitations(GetDossierNumber());
 
    // Check dossier if version is lower than current 
    if(GetDossierVersion()!=CT_VERSION) {
      dossier_checkintegrity();
      SetDossierVersion(CT_VERSION);
    }
    //dino_inspect(GetDossierNumber());
    start_autosave();
    return 1; // OK
  }
  return 0;
}


function CreateDossier(name,lang,pri,ordnum) {
  stop_autosave();  

  if(dos_loadxmlinit(XMLDOMDOS,"defs/dossier.xml")=="error") {
    return 0;
  } 

  DOSSIER=XMLDOMDOS.selectSingleNode('dossier');
  CLAIMSET=null;
  DOCS=DOSSIER.selectSingleNode('documents').childNodes;
  
  SetDossierVersion(CT_VERSION);  
  SetDossierNumber(NormalizeDossierNumber(name));
  SetDossierOrdNum(ordnum);
  SetDossierPri(pri);
  SetDossierLang(lang);

  start_autosave();      
}

function GetDossier() {
  return DOSSIER;
}
function SetDossier(s) {
  DOSSIER=s;
}

function NormalizeDossierNumber(dn) {
	return dn.toUpperCase();
}

function GetDossierNumber() {
  return (DOSSIER && DOSSIER.getAttribute("number")) || "";
}

function SetDossierNumber(num) {
  DOSSIER.setAttribute("number",NormalizeDossierNumber(num));
}

function GetDossierPN() {
  return DOSSIER.getAttribute("PN");
}

function SetDossierPN(num) {
  DOSSIER.setAttribute("PN",num.toUpperCase());
}

function GetDossierVersion() {
  return (DOSSIER && DOSSIER.getAttribute("version")) || "";
}

function SetDossierVersion(v) {
  return DOSSIER.setAttribute("version",v);
}


// Hanlde dossier important dates

// dossier birth
function GetDossierPri() {
  return DOSSIER.getAttribute("priority");
}

function SetDossierPri(pri) {
  DOSSIER.setAttribute("priority",pri);
}

// dossier death
function GetDossierEndDate(dn) {
  if(!dn) return DOSSIER.getAttribute("edate") || "";
  var _dos=DOSSIER; // uggly
  if(XML_DSS._LoadDossier(dn)) {
    var endd=GetDossierEndDate();
    DOSSIER=_dos;
    return endd;
  }
  return "";
}

function SetDossierEndDate(d,dn) {
  if(!dn || dn==GetDossierNumber()) {
    DOSSIER.setAttribute("edate",d);
  } else {
    var _dos=DOSSIER; // uggly
    if(XML_DSS._LoadDossier(dn)) {
      DOSSIER.setAttribute("edate",d);
      DOSSIER=_dos;
    }
  }
}


function IsDossierDead(dn) {
  return GetDossierEndDate(dn);
}

function GetDossierLang() {
  return DOSSIER.getAttribute("lang");
}

function SetDossierLang(lang) {
  DOSSIER.setAttribute("lang",lang);
}


function GetDossierOrdNum() {
  return DOSSIER.getAttribute("ordnum")|| "??";
}

function _GetDossierOrdNum() {
  return DOSSIER.getAttribute("ordnum")|| 0;
}

function SetDossierOrdNum(num) {
  DOSSIER.setAttribute("ordnum",num);
}

function GetDossierTitle() {
  return DOSSIER.getAttribute("title") || "";
}

function SetDossierTitle(txt) {
  DOSSIER.setAttribute("title",txt);
}

function GetDossierApplicant() {
  return DOSSIER.getAttribute("applicant") || "";
}

function SetDossierApplicant(txt) {
  DOSSIER.setAttribute("applicant",txt);
}


function GetDossierKeywords() {
  return DOSSIER.getAttribute("keywords") || "";
}

function SetDossierKeywords(num) {
  DOSSIER.setAttribute("keywords",num);
}

function GetDossierDescription() {
  var node=DOSSIER.selectSingleNode("description");
  if(node) return node.text;
  return "";
}

function SetDossierDescription(txt) {
  var node=DOSSIER.selectSingleNode("description");
  if(!node) {
    node=XMLDOMDOS.createElement("description");
    DOSSIER.appendChild(node);
  }    
  node.text=txt;
}


function dossier_checkintegrity(){
  var cs_iter= new claimsets_iterator();
  while(!cs_iter.end()) {
    cs_iter.select();
    CheckClaimSetIntegrity();
    cs_iter.next();
  }
}





function dossier_iterator(dir) {
  this._dossiers=dos_dir(dir || GetDossiersDir(),".xml");
  this._idx=0;


  this.next = function() {
    while(!XML_DSS._LoadDossier(this._dossiers[this._idx++],"quiet")) {
      if(this.end()){
	return;
      }
    }
  }
  this.end = function() {
    return this._idx>this._dossiers.length;
  }

  this.getPri = function(){
    return prettyDate(GetDossierPri()); 
  };

  this.getOrdNum = function(){
    return GetDossierOrdNum(); 
  };

  this.getNumber = function(){
    return GetDossierNumber(); 
  };
  
  this.getTitle  = function(){
    return GetDossierTitle(); 
  };

  this.getEndDate = function() {
    return GetDossierEndDate();
  }

  this.setEndDate = function(d) {
    SetDossierEndDate(prettyDate(d));
  }

  this.length = function () {
    return this._dossiers.length;
  }
  if(this._dossiers.length>=1) {
    this.next();
  }  
}



//-------------------------------------------------------------------------------

// Sort using rwd 
function dossiersortnum(a,b) {
  return parseInt(a.getAttribute("on")) - parseInt(b.getAttribute("on"));
}

function antidossiersortnum(a,b) {
  return parseInt(b.getAttribute("on")) - parseInt(a.getAttribute("on"));
}


function add_doscacheentry(dn,on,pri,last,title,edate) {
  if(!XML_DSS.CACHEROOT) {
    loaddossiercache(GetDossiersDir());
  }
  var act=XML_DSS.DOSCACHE.createElement("dc");
  act.setAttribute("dn",dn);
  act.setAttribute("on",on);
  act.setAttribute("pri",pri);
  act.setAttribute("last",last);
  act.setAttribute("title",title);
  if(edate) act.setAttribute("edate",edate);
  XML_DSS.CACHEROOT.appendChild(act);
  return act;
}

function find_doscacheentry(dn) {
  return XML_DSS.CACHEROOT && XML_DSS.CACHEROOT.selectSingleNode("/dossiers/dc[ @dn=\""+dn+"\"]");
}

function delete_doscacheentry(node) {
  XML_DSS.CACHEROOT.removeChild(node);
}

function dossier_cacheiterator(dir,order) {
  this._idx=0;
  this._dossiers;

  this.next = function() {
    this._dossiers[this._idx++];
  }
  
  this.end = function() {
    return this._idx>=this._dossiers.length;
  }

  this.reset = function() {
    this._idx=0;
    this._dossiers=XML_DSS.CACHEARRAY;
  }

  this.getPri = function(){
    return prettyDate(this._dossiers[this._idx].getAttribute("pri"));
  };

  this.getOrdNum = function(){
    return this._dossiers[this._idx].getAttribute("on") || "??"; 
  };

  this.getNumber = function(){
    return this._dossiers[this._idx].getAttribute("dn"); 
  };

  this.getEndDate = function () {
    return this._dossiers[this._idx].getAttribute("edate"); 
  }

  this.getTitle  = function(){
    return this._dossiers[this._idx].getAttribute("title"); 
  };

  this.getLastAction = function() {
    return this._dossiers[this._idx].getAttribute("last");
  } 

  this.sort = function (field) {
    SetSortDossierFunct(field);
    XML_DSS.CACHEARRAY.sort(XML_DSS._setdossiersort);
    this.reset();
  }

  // init 

  if(!XML_DSS.DOSCACHE || XML_DSS.CACHEDIR !=dir ) {
    loaddossiercache(dir);
    XML_DSS.CACHEDIR=dir;
    XML_DSS.CACHEARRAY.sort(XML_DSS._setdossiersort);
  } 

  this._dossiers=XML_DSS.CACHEARRAY;   
}

function deletedossiercache() {
  XML_DSS.DOSCACHE="";
  if(dos_isfile(XML_DSS.CACHEFILE)) {
    dos_rm(XML_DSS.CACHEFILE);
  }
}

function loaddossiercache(dir) {
  XML_DSS.DOSCACHE=new ActiveXObject("Msxml2.DOMDocument");
  if(dos_isfile(XML_DSS.CACHEFILE)) {
    XML_DSS.DOSCACHE.load(XML_DSS.CACHEFILE);
    XML_DSS.CACHEROOT=XML_DSS.DOSCACHE.selectSingleNode("dossiers");
    if(XML_DSS.CACHEROOT) {
      XML_DSS.CACHEARRAY= new Array();
      for(var node=0; node < XML_DSS.CACHEROOT.childNodes.length; node++) {
	XML_DSS.CACHEARRAY.push(XML_DSS.CACHEROOT.childNodes[node]);
      }
      return;
    }
  }
  createdossiercache(dir);  
}

// update current dossier cache 
function updatedossiercache() {
  var dn=GetDossierNumber();
  var node=find_doscacheentry(dn);
  var edate="";
  var last_type="";
  if(!node) {
    CaesarImportCitations(dn,"quiet");
    node=add_doscacheentry(dn,GetDossierOrdNum(),GetDossierPri(),"",beautytitle(GetDossierTitle()),GetDossierEndDate());
    XML_DSS.CACHEARRAY.push(node);
  } 
  last_action=FindLastAction(dn);
  if(!last_action.end()) {
    last_type=last_action.getTYPE();
    if(action_isdead(last_type)) {
      edate=last_action.getDDATE();
    }
  } else {
    last_type="";
    edate=GetDossierEndDate();
  }

  node.setAttribute("last",last_type);

  node.setAttribute("edate",edate);
  XML_DSS.DOSCACHE.save(XML_DSS.CACHEFILE);

}

function createdossiercache(dir) {
    XML_DSS.DOSCACHE=new ActiveXObject("Msxml2.DOMDocument");
    XML_DSS.CACHEROOT=XML_DSS.DOSCACHE.createElement("dossiers");
    XML_DSS.DOSCACHE.appendChild(XML_DSS.CACHEROOT);
    XML_DSS.CACHEROOT.setAttribute("sort","getOrdNum");
    XML_DSS.CACHEROOT.setAttribute("dir",dir);
    XML_DSS.CACHEARRAY= new Array();
    var doss_iter= new array_iterator(dos_dir(dir,".xml"));
    var last_action="",last_type="",edate="";
    while(!doss_iter.end()) { 
      if(XML_DSS._LoadDossier(doss_iter.getValue(),"quiet")) {
	last_action=FindLastAction(doss_iter.getValue());
	edate="";
	if(!last_action.end()) {
	  last_type=last_action.getTYPE();
	  if(action_isdead(last_type)) {
	    edate=last_action.getDDATE();
	  }
	} else {
	  last_type="";
	  edate=GetDossierEndDate();
	}
	XML_DSS.CACHEARRAY.push(add_doscacheentry(doss_iter.getValue(),
					  _GetDossierOrdNum(),
					  GetDossierPri(),
					  last_type,
					  beautytitle(GetDossierTitle()),
					  edate));
      }
      doss_iter.next();
    }
    XML_DSS.DOSCACHE.save(XML_DSS.CACHEFILE);
    return XML_DSS.CACHEARRAY;
}     

function beautytitle(title) {
  var txt_iter= new text_iterator(title,""," ");
  var out=new List();
  if(!txt_iter.end()) { 
    out.push(firstchar(txt_iter.getValue()).toUpperCase()+rmfirstchar(txt_iter.getValue().toLowerCase()));
    txt_iter.next();
  }
  while(!txt_iter.end()) {  
    out.push(txt_iter.getValue().toLowerCase());
    txt_iter.next();
  }
  return out.getText(" "," ");
}


function dossiersortxdate(attr,a,b) {
  if(!a.getAttribute(attr)) {
    return 1;
  }
  if(!b.getAttribute(attr)) {
    return -1;
  }
  return str2Date(a.getAttribute(attr)) - str2Date(b.getAttribute(attr));
}

function antidossiersortxdate(attr,a,b) {
  if(!a.getAttribute(attr)) {
    return 1;
  }
  if(!b.getAttribute(attr)) {
    return -1;
  }
  return str2Date(b.getAttribute(attr)) - str2Date(a.getAttribute(attr));
  //return !actionsortxdate(attr,a,b);
}


function dossiersortalpha(attr,a,b) {
  //return a.getAttribute(attr) > b.getAttribute(attr);
  // alert("compare "+attr);
  var str1=a.getAttribute(attr);
  var str2=b.getAttribute(attr);
  //alert("compare "+attr+ " "+str1+" and "+str2);
  for(var i=0; i< str1.length && str2.length; i++) {
    if(str1.charAt(i) < str2.charAt(i)) {
      return -1;
    }
    if(str1.charAt(i) > str2.charAt(i)) {
      return 1;
    }
  }
  return str1.length-str2.length;
} 


var dossiersortdnup    = function(a,b) { return dossiersortalpha("dn",a,b);};
var dossiersortdndown = function(a,b) { return dossiersortalpha("dn",b,a);};
var dossiersortlastup    = function(a,b) { return dossiersortalpha("last",a,b);};
var dossiersortlastdown = function(a,b) { return dossiersortalpha("last",b,a);};
var dossiersorttitleup    = function(a,b) { return dossiersortalpha("title",a,b);};
var dossiersorttitledown = function(a,b) { return dossiersortalpha("title",b,a);};
var dossiersortpriup    = function(a,b) { return dossiersortxdate("pri",a,b);};
var dossiersortpridown = function(a,b) { return antidossiersortxdate("pri",a,b);};


function SetSortDossierFunct(f) {
  switch(f) {
  case "on":
    if(XML_DSS._setdossiersort==dossiersortnum) {
      XML_DSS._setdossiersort=antidossiersortnum;
    } else {
      XML_DSS._setdossiersort=dossiersortnum;
    }      
    break;
  case "dn":
    if(XML_DSS._setdossiersort==dossiersortdnup) {
      XML_DSS._setdossiersort=dossiersortdndown;
    } else {
      XML_DSS._setdossiersort=dossiersortdnup;
    }      
    break;
  case "pri":
    if(XML_DSS._setdossiersort==dossiersortpriup) {
      XML_DSS._setdossiersort=dossiersortpridown;
    } else {
      XML_DSS._setdossiersort=dossiersortpriup;
    }      
    break;
  case "title":
    if(XML_DSS._setdossiersort==dossiersorttitleup) {
      XML_DSS._setdossiersort=dossiersorttitledown;
    } else {
      XML_DSS._setdossiersort=dossiersorttitleup;
    }      
    break;
  case "last":
    if(XML_DSS._setdossiersort==dossiersortlastup) {
      XML_DSS._setdossiersort=dossiersortlastdown;
    } else {
      XML_DSS._setdossiersort=dossiersortlastup;
    }      
    break;
  }

}



var DOSSEARCH=new ActiveXObject("Msxml2.DOMDocument");
DOSSEARCH.setProperty("SelectionLanguage", "XPath"); 

function dossier_search(name,txt) {
  DOSSEARCH.load(GetDossiersDir()+name+".xml");

  if(DOSSEARCH.parseError.errorCode != 0) { 
    //alert(name +"not found");
    return false;
  } 
  
  var citer= new char_iterator(txt);
  var op="";
  var field="";
  var val="";
  var second=0;
  while(!citer.end()) {
    switch(citer.getValue()) {
      case "=":
      case "!":
      case ">":
      case "<":
	op+=citer.getValue();
	second=1;
	break;
     default:
	if(second) {
	   val+=citer.getValue();
        } else {
	   field+=citer.getValue();
        }      
    }
    citer.next();
  }
  if(!val) {
    val=field;
    field="";
  }
  
  switch(field.toUpperCase()) {
  case "CL":       
    var nodes=DOSSEARCH.selectSingleNode("/dossier/claim_set/claims/claim[ @clnum=\""+(parseInt(val))+"\"]");        
    var morenodes=DOSSEARCH.selectSingleNode("/dossier/claim_set/claims/claim[ @clnum=\""+(parseInt(val)+1)+"\"]");
    switch(op) {
    case "==": 
    case "=":
      return nodes && !morenodes;
      break;
    case ">=":
      return nodes;
    case "<=":
      return !morenodes; 
    case "<":
      return !nodes;
    case ">":
      return morenodes;
    }
    break;
  case "V":
    return DOSSEARCH.selectSingleNode("/dossier[ @version = \""+val+"\"]");        
  case "NU":
  case "G":
    return DOSSEARCH.selectSingleNode("/dossier/claim_set/claims/claim[@G "+op+"\""+val.toUpperCase()+"\"]");
  case "AN":
    return DOSSEARCH.selectSingleNode("/dossier[@number=\""+val.toUpperCase()+"\"]") 
      || DOSSEARCH.selectSingleNode("/dossier/claim_set[@number=\""+val.toUpperCase()+"\"]");
  case "ON":
    return DOSSEARCH.selectSingleNode("/dossier[@ordnum=\""+val+"\"]");
  case "CT":
    return DOSSEARCH.selectSingleNode("/dossier/claim_set/claims/claim/clsdocs/cldoc[@docid=\""+val.toUpperCase()+"\"]");
  default: // case sensitive !
    return DOSSEARCH.selectSingleNode("/dossier/claim_set/claims/claim/features/feature[contains(@desc,'"+val+"')]");
  } 
}

function search_help() {
	return "AN = string  : app number\nON = num : ord num\nCL op num: number of claims\nCT = doc  : citing document doc\n txt    : containing string txt\n"+
	"where op is {=,>=,<=,<,>}";
}



  
